package com.smedi.ismedi.notification.core.port.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.smedi.ismedi.notification.core.domain.aggregatemodel.SmsTemplate;
import com.smedi.ismedi.notification.core.infrastructure.constant.CustomError;
import com.smedi.ismedi.notification.core.port.service.SmsClientRemoteApiService;
import com.smedi.ismedi.web.starter.exception.LogicException;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: xulinjun
 * @Date: 2021-6-21 11:15
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SmsClientRemoteApiServiceImpl implements SmsClientRemoteApiService {
    private final SmsClient smsClient;

    @Value("${tencent-could.appId}")
    private String appId;

    @Value("${message.enable}")
    private boolean MESSAGE_ENABLE;

    @Override
    public Long addSmsTemplate(SmsTemplate smsTemplate) {
        Map<String, Object> map = new HashMap<>();
        map.put("TemplateName", smsTemplate.getTemplateName());
        map.put("TemplateContent", smsTemplate.getTemplateContent());
        map.put("SmsType", 0); // 默认普通短信
        map.put("International", 0); // 默认国内短信
        map.put("Remark", smsTemplate.getRemark()); // 备注说明

        // 获取请求
        try {
            AddSmsTemplateRequest req = AddSmsTemplateRequest.fromJsonString(JSON.toJSONString(map), AddSmsTemplateRequest.class);
            AddSmsTemplateResponse resp = smsClient.AddSmsTemplate(req);
            log.info("AddSmsTemplateResponse >>> {}", AddSmsTemplateResponse.toJsonString(resp));

            return Long.valueOf(resp.getAddTemplateStatus().getTemplateId());
        } catch (TencentCloudSDKException e) {
            log.error("AddSmsTemplateResponse Error >>> {}", e);
            throw LogicException.raise(CustomError.UN_HANDLER_EXCEPTION, e);
        }
    }

    @Override
    public void modifySmsTemplate(SmsTemplate smsTemplate) {
        ModifySmsTemplateRequest req = new ModifySmsTemplateRequest();
        req.setTemplateId(smsTemplate.getTencentTemplateId()); // 腾讯模板id
        req.setTemplateName(smsTemplate.getTemplateName());   // 模板名称
        req.setTemplateContent(smsTemplate.getTemplateContent()); // 模板内容
        req.setSmsType(0L); // 短信格式
        req.setInternational(0L); // 国际化
        req.setRemark(smsTemplate.getRemark()); // 备份

        try {
            ModifySmsTemplateResponse resp = smsClient.ModifySmsTemplate(req);
            log.info(" response -> {}", ModifySmsTemplateResponse.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
            log.error("ModifySmsTemplateResponse >>> {}", e);
            throw LogicException.raise(CustomError.UN_HANDLER_EXCEPTION, e);
        }
    }

    @Override
    public SendSmsResponse send(List<String> receivers, List<String> parameters, Long templateId, String sign, String batchId) {
        // 刷新接受人的手机号格式
        List<String> formatted = new ArrayList<>();
        for (String receiver : receivers) {
            if (receiver.length() > 11) {
                formatted.add((receiver.indexOf("+") < 0 ? "+" + receiver : receiver));
            } else {
                formatted.add("+86" + receiver);
            }
        }

        SendSmsRequest req = new SendSmsRequest();
        req.setPhoneNumberSet(formatted.toArray(new String[formatted.size()])); // 电话号码
        req.setTemplateID(String.valueOf(templateId));
        req.setSessionContext(batchId); // 代表uuid记录
        req.setSign(sign);
        // 参数信息
        if (parameters.size() > 0) {
            req.setTemplateParamSet(parameters.toArray(new String[parameters.size()]));
        }
        req.setSmsSdkAppid(appId); // appId

        try {
            SendSmsResponse response = new SendSmsResponse();
            if (MESSAGE_ENABLE) {
                response = smsClient.SendSms(req);
            }
            log.info(" SendSmsResponse >>> {}", SendSmsResponse.toJsonString(response));
            return response;
        } catch (TencentCloudSDKException e) {
            log.error("SendSmsResponse Error >>> {}", e);
            throw LogicException.raise(CustomError.UN_HANDLER_EXCEPTION, e);
        }
    }

    @Override
    public void deleteSmsTemplate(Long tencentTemplateId) {
        DeleteSmsTemplateRequest req = new DeleteSmsTemplateRequest();
        req.setTemplateId(tencentTemplateId);
        try {
            DeleteSmsTemplateResponse resp = smsClient.DeleteSmsTemplate(req);
            log.info("DeleteSmsTemplateResponse >>> {}, tencentTemplateId >>> {}", DeleteSmsTemplateResponse.toJsonString(resp), tencentTemplateId);
        } catch (TencentCloudSDKException e) {
            log.error("DeleteSmsTemplateResponse Error >>> {}", e);
            throw LogicException.raise(CustomError.UN_HANDLER_EXCEPTION, e);
        }
    }

    @Override
    public DescribeSmsTemplateListResponse getSmsTemplateStatus(List<Long> tencentTemplateIds) {
        Long[] templateIdSets = tencentTemplateIds.toArray(new Long[tencentTemplateIds.size()]);

        DescribeSmsTemplateListRequest req = new DescribeSmsTemplateListRequest();
        req.setTemplateIdSet(templateIdSets);
        req.setInternational(0L);

        try {
            DescribeSmsTemplateListResponse resp = smsClient.DescribeSmsTemplateList(req);
            return resp;
        } catch (TencentCloudSDKException e) {
            log.error("DescribeSmsTemplateListResponse Error >>> {}", e);
            throw LogicException.raise(CustomError.UN_HANDLER_EXCEPTION, e);
        }
    }
}
